package com.zjw.demo.vertx.starter.template.service;

import com.zjw.demo.vertx.starter.annotation.core.Inject;
import com.zjw.demo.vertx.starter.annotation.core.Service;
import com.zjw.demo.vertx.starter.service.IService;
import com.zjw.demo.vertx.starter.service.ServiceDispatcher;
import com.zjw.demo.vertx.starter.smi.IFutureTask;
import com.zjw.demo.vertx.starter.template.bean.Response;
import com.zjw.demo.vertx.starter.template.bean.User;
import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class LoginService implements IService {

  private static final Pattern usernameRegex = Pattern.compile("[0-9].+");

  @Inject
  public MysqlService mysqlService;

  @Override
  public void onStart(Vertx vertx) {

  }

  public void login(String username, String password, RoutingContext ctx) {
    //查询数据库
    Matcher matcher = usernameRegex.matcher(username);
    if (!matcher.find()) {
      //invalid username！！！
      ctx.response().end(Response.ofFail("error").toJson().toString());
      return;
    }
    mysqlService.queryUser(username, new IFutureTask<>() {
      @Override
      public void onResult(List<User> result) {
        boolean equals = result.get(0).password.equals(password);
        if (equals) {
          ctx.response().end(Response.ofSuccess("success").toJson().toString());
        }else{
          ctx.response().end(Response.ofFail("error").toJson().toString());
        }
      }

      @Override
      public void onError(Throwable throwable) {
        ctx.response().end(Response.ofFail("error").toJson().toString());
      }
    });
  }
}
